package com.yipei.business.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yipei.business.domain.MlTradeDealOrder;
import com.yipei.business.domain.MlTradeEntrustOrder;
import com.yipei.business.service.IMlTradeEntrustOrderService;
import com.yipei.business.vo.DeliveryOrderVo;
import com.yipei.business.vo.EntrustOrderVo;
import com.yipei.common.annotation.Log;
import com.yipei.common.annotation.RepeatSubmit;
import com.yipei.common.core.controller.BaseController;
import com.yipei.common.core.domain.AjaxResult;
import com.yipei.common.core.page.TableDataInfo;
import com.yipei.common.enums.BusinessType;
import com.yipei.common.utils.SecurityUtils;
import com.yipei.common.utils.poi.ExcelUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.Max;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 委托订单Controller
 *
 * @author yipei
 * @date 2024-12-21
 */
@RestController
@RequestMapping("/business/order")
@Api(tags = "委托订单", description = "委托订单")
public class MlTradeEntrustOrderController extends BaseController {
    @Autowired
    private IMlTradeEntrustOrderService mlTradeEntrustOrderService;

    /**
     * 查询委托订单列表
     */
    //@PreAuthorize("@ss.hasPermi('business:order:list')")
    @ApiOperation("委托订单获取数据")
    @GetMapping("/list")
    public TableDataInfo list(MlTradeEntrustOrder mlTradeEntrustOrder) {
        startPage();
        List<MlTradeEntrustOrder> list = mlTradeEntrustOrderService.selectMlTradeEntrustOrderList(mlTradeEntrustOrder);
        return getDataTable(list);
    }

    /**
     * 导出委托订单列表
     */
    //@PreAuthorize("@ss.hasPermi('business:order:export')")
    @ApiOperation("委托订单导出数据")
    @Log(title = "委托订单", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, MlTradeEntrustOrder mlTradeEntrustOrder) {
        List<MlTradeEntrustOrder> list = mlTradeEntrustOrderService.selectMlTradeEntrustOrderList(mlTradeEntrustOrder);
        ExcelUtil<MlTradeEntrustOrder> util = new ExcelUtil<MlTradeEntrustOrder>(MlTradeEntrustOrder.class);
        util.exportExcel(response, list, "委托订单数据");
    }

     /**
     * 获取委托订单详细信息
     */
    //@PreAuthorize("@ss.hasPermi('business:order:query')")
    @ApiOperation("委托订单通过ID获取数据")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(mlTradeEntrustOrderService.selectMlTradeEntrustOrderById(id));
    }

    /**
     * 新增委托订单
     */
    //@PreAuthorize("@ss.hasPermi('business:order:add')")
    @ApiOperation("委托订单新增数据")
    @Log(title = "委托订单", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody MlTradeEntrustOrder mlTradeEntrustOrder) {
        return toAjax(mlTradeEntrustOrderService.insertMlTradeEntrustOrder(mlTradeEntrustOrder));
    }

    @ApiOperation("委托订单新增数据/参数对象:订单数据mlTradeEntrustOrder,全部数据mlKLineMasterVo")
//    @Log(title = "委托订单", businessType = BusinessType.INSERT)
    @PostMapping("/addEntrustOrder")
    @RepeatSubmit
    public AjaxResult addEntrustOrder(@RequestBody EntrustOrderVo entrustOrderVo) throws Exception {
        AjaxResult ajaxResult = mlTradeEntrustOrderService.addEntrustOrder(entrustOrderVo);
        return AjaxResult.success(ajaxResult);
//        return toAjax(mlTradeEntrustOrderService.insertMlTradeEntrustOrder(mlTradeEntrustOrder));
    }

    /**
     * 修改委托订单
     */
    //@PreAuthorize("@ss.hasPermi('business:order:edit')")
    @ApiOperation("委托订单修改数据")
    @Log(title = "委托订单", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody MlTradeEntrustOrder mlTradeEntrustOrder) {
        return toAjax(mlTradeEntrustOrderService.updateMlTradeEntrustOrder(mlTradeEntrustOrder));
    }

    /**
     * 删除委托订单
     */
    //@PreAuthorize("@ss.hasPermi('business:order:remove')")
    @ApiOperation("委托订单删除数据")
    @Log(title = "委托订单", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(mlTradeEntrustOrderService.deleteMlTradeEntrustOrderByIds(ids));
    }

    //@PreAuthorize("@ss.hasPermi('business:order:list')")
    @ApiOperation("查询可撤单的委托订单")
    @GetMapping("/cancelList")
    public AjaxResult cancelList(MlTradeEntrustOrder mlTradeEntrustOrder) {
//        startPage();
//        List<MlTradeEntrustOrder> list = mlTradeEntrustOrderService.selectMlTradeEntrustOrderList(mlTradeEntrustOrder);
//        return getDataTable(list);
        String tdAcc = SecurityUtils.getLoginMember().getMlTradeAccount().getTdAcc();
        LambdaQueryWrapper<MlTradeEntrustOrder> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.and(i -> i.eq(MlTradeEntrustOrder::getTdAcc,tdAcc )).orderByDesc(MlTradeEntrustOrder::getCreateTime);
        List<MlTradeEntrustOrder> list = mlTradeEntrustOrderService.list(lambdaQueryWrapper);
        return AjaxResult.success(list);
    }


    @ApiOperation("委托订单撤销")
//    @Log(title = "委托订单", businessType = BusinessType.INSERT)
    @PostMapping("/entrustOrderCancel")
    public AjaxResult entrustOrderCancel(@RequestBody MlTradeEntrustOrder mlTradeEntrustOrder) throws Exception {
        List<BigDecimal> num=new ArrayList<>();
        num.add(BigDecimal.ZERO);
        num.add(BigDecimal.ONE);
        num.add(new BigDecimal(2));
        if (!num.stream().anyMatch(bd -> bd.compareTo(mlTradeEntrustOrder.getWtZt()) == 0)){
            throw new Exception("此状态下不允许撤单！");
        }
        mlTradeEntrustOrderService.entrustOrderCancel(String.valueOf(mlTradeEntrustOrder.getId()));
        return AjaxResult.success("撤单成功");
//        return toAjax(mlTradeEntrustOrderService.insertMlTradeEntrustOrder(mlTradeEntrustOrder));
    }


    @ApiOperation("获取委托单")
//    @Log(title = "委托订单", businessType = BusinessType.INSERT)
    @GetMapping("/getTodayOrder")
    public AjaxResult getTodayOrder() {
        String tdAcc = SecurityUtils.getLoginMember().getMlTradeAccount().getTdAcc();
        SimpleDateFormat dateStr = new SimpleDateFormat("yyyy-MM-dd");
        String date = dateStr.format(new Date());
        String e_time= date+" 24:59:59";
        String s_time=date+" 00:00:00";
        List<MlTradeEntrustOrder> list = mlTradeEntrustOrderService.lambdaQuery().eq(MlTradeEntrustOrder::getTdAcc,tdAcc)
                .ge(MlTradeEntrustOrder::getCreateTime,s_time).le(MlTradeEntrustOrder::getCreateTime,e_time).list();
         if(CollectionUtils.isEmpty(list)){
             return AjaxResult.error("未获取到今日委托数据！");
         }else {
             return AjaxResult.success(list);
         }
    }

    @ApiOperation("获取历史委托单据")
//    @Log(title = "委托订单", businessType = BusinessType.INSERT)
    @GetMapping("/entrustHistoryOrder")
    public AjaxResult getEntrustHistoryOrder(@RequestParam(name = "s_time", required = true) String s_time,@RequestParam(name = "e_time", required = true) String e_time ) {
        String tdAcc = SecurityUtils.getLoginMember().getMlTradeAccount().getTdAcc();
        e_time= e_time+" 24:59:59";
        List<MlTradeEntrustOrder> list = mlTradeEntrustOrderService.lambdaQuery().eq(MlTradeEntrustOrder::getTdAcc,tdAcc)
                .ge(MlTradeEntrustOrder::getCreateTime,s_time).le(MlTradeEntrustOrder::getCreateTime,e_time)
                .list();
        if(CollectionUtils.isEmpty(list)){
            return AjaxResult.error("未获取到时间范围内委托订单！");
        }else {
            return AjaxResult.success(list);
        }
    }


    @ApiOperation("获得交割明细数据")
//    @Log(title = "委托订单", businessType = BusinessType.INSERT)
    @GetMapping("/getDeliveryOrder")
    public AjaxResult getDeliveryOrderVo(@RequestParam(name = "s_time", required = true) String s_time,@RequestParam(name = "e_time", required = true) String e_time) {
        List<DeliveryOrderVo> list=  mlTradeEntrustOrderService.getDeliveryOrderVo(s_time,e_time);
        return AjaxResult.success (list);
    }

    /**
     *创建委托交易数据
     */
    @ApiOperation("创建委托交易数据")
    @PostMapping("/entrustOrderInsert")
    public AjaxResult entrustOrderInsert(@RequestBody MlTradeEntrustOrder mlTradeEntrustOrder) throws Exception {
        AjaxResult ajaxResult = mlTradeEntrustOrderService.entrustOrderInsert(mlTradeEntrustOrder);
        return AjaxResult.success(ajaxResult);
    }
}
